package com.remote.server.handle;


import com.remote.common.RemoteFactory;
import com.remote.common.command.Commands;
import com.remote.common.model.Request;
import com.remote.common.model.ServerClientInfo;
import com.remote.common.util.Utils;
import io.netty.channel.ChannelHandlerContext;

import java.util.Collection;

import static com.remote.common.constant.Constants.CLIENT_INFO;
import static com.remote.common.constant.MessageConstants.MASTER_CONNECTION_LOST;
import static com.remote.common.constant.MessageConstants.WRONG_CONNECT_VALUE;

/**
 * 截屏发送处理
 */
public class ScreenCommandHandler extends BaseServerHandler {

    public ScreenCommandHandler(RemoteFactory remoteFactory) {
        super(remoteFactory);
    }

    @Override
    protected void handleO(ChannelHandlerContext ctx, Request inbound) {
        //检查请求的内容
        if (!(inbound.getValue() instanceof byte[])) {
            final String should_be_bufferedImage = String.format("%s %s %s", WRONG_CONNECT_VALUE, inbound.getValue(), "should be BufferedImage");
            error(inbound, should_be_bufferedImage);
            Utils.sendError(ctx.channel(), inbound, should_be_bufferedImage);
            return;
        }

        final ServerClientInfo clientInfo = ctx.channel().attr(CLIENT_INFO).get();
        if (clientInfo == null) {
            error(inbound, MASTER_CONNECTION_LOST);
            Utils.sendError(ctx.channel(), inbound, MASTER_CONNECTION_LOST);
            return;
        }

        Collection<ChannelHandlerContext> handlerContexts = clientInfo.controlContexts().values();
        for (ChannelHandlerContext handlerContext : handlerContexts) {
            if (handlerContext != null && handlerContext.channel().isOpen()) {
                handlerContext.writeAndFlush(Utils.buildResponse(inbound, Commands.SCREEN, inbound.getValue()));
                continue;
            }
        }
    }
}
